<template>
  <view class="fix-top-window">
    <view class="uni-header">
      <view class="uni-sub-title">任务列表</view>
      <view class="hor-layout-center" style="margin-right: 10px">
        <el-select v-model="queryPara.selectBuild" @change="changeSelectPara" clearable size="small"
                   placeholder="请选择楼栋号"
                   class="info-select">
          <el-option v-for="item in buildings" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <!--        <el-select v-model="queryPara.selectUnit" @change="getTaskList" clearable size="small" placeholder="请选择单元号"-->
        <!--                   class="info-select">-->
        <!--          <el-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
        <!--        </el-select>-->
        <view style="width: 30vw"></view>
        <el-button size="small" type="primary" @click="createTask">新增任务</el-button>
      </view>
    </view>
    <view class="uni-container">
      <el-button type="danger" size="mini" style="margin-bottom: 10px" v-show="showDeleteBtn" @click="deleteTaskBatch">
        批量删除
      </el-button>
      <el-table v-loading="loadingList" :data="houseList" @selection-change="handleSelectionChange" border
                element-loading-background="rgba(255, 255, 255, 0.1)" :header-cell-style="getTableHeader">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="task_title" label="任务名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="task_desc" label="任务描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="build_nums_str" label="任务楼号"></el-table-column>
        <el-table-column prop="task_type_str" label="任务类型"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-upload2" v-if="canPublishTask(scope.row)"
                       @click="updateTaskState(scope.row,'发布')">发布
            </el-button>
            <el-button type="warning" size="mini" icon="el-icon-download" v-else
                       @click="updateTaskState(scope.row,'撤回')">撤回
            </el-button>
            <el-button type="primary" size="mini" v-if="canPublishTask(scope.row)"
                       @click="toTaskDetail(scope.row,'修改')">修改
            </el-button>
            <el-button type="success" size="mini" v-else
                       @click="toTaskDetail(scope.row,'详情')">详情
            </el-button>
            <el-button type="danger" size="mini" @click="deleteTaskById(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <view class="hor-layout-center-all" style="margin-top:15px;">
        <span class="total-view">共{{ queryPara.total }}条</span>
        <el-pagination background small layout="sizes, prev, pager, next"
                       :current-page="queryPara.current" :page-size="queryPara.size" :page-sizes="[10, 20, 30]"
                       :total="queryPara.total" @current-change="handleCurrentChange"
                       @size-change="handleSizeChange"></el-pagination>
      </view>
    </view>
  </view>
</template>

<script>
import { data } from "@/common/house"

export default {
  name: "list",
  data() {
    return {
      queryPara: {selectBuild: '', selectUnit: '', total: 0, current: 1, size: 10},
      buildings: data.buildings,
      unitList: data.unitList,
      houseList: [],
      taskTypes: data.taskTypes,
      selTaskIds: [],
      loadingList: false
    }
  },
  onShow() {
    this.getTaskList()
  },
  computed: {
    getTableHeader() {
      return {background: '#F3F4F7', color: '#555'}
    },
    showDeleteBtn() {
      return this.selTaskIds.length > 0
    }
  },
  methods: {
    canPublishTask(task) {
      return task.state === '0'
    },
    handleSelectionChange(val) {
      this.selTaskIds = val.map(item => item._id)
    },
    handleCurrentChange(val) {
      this.queryPara.current = val
      this.getTaskList()
    },
    handleSizeChange(val) {
      this.queryPara.size = val
      this.getTaskList()
    },
    changeSelectPara() {
      this.queryPara.size = 10
      this.queryPara.current = 1
      this.getTaskList()
    },
    createTask() {
      uni.navigateTo({url: '/pages/plot/task/add'})
    },
    toTaskDetail(task, flag) {
      let update = flag === '修改' ? '修改' : ''
      uni.navigateTo({url: `/pages/plot/task/add?taskId=${task._id}&update=${update}`})
    },
    getTaskList() {
      this.loadingList = true
      let {selectBuild, selectUnit, current, size} = this.queryPara
      let build_nums = selectBuild ? selectBuild : this.$dbCmd.neq('')
      let params = {build_nums}
      let skip = (current - 1) * size
      console.log("params", params)
      this.$db.collection('plot-task').where(params).skip(skip).limit(size)
          .orderBy("create_date", "desc").get({"getCount": true})
          .then(res => {
            let list = res.result.data
            this.queryPara.total = res.result.count
            this.houseList = list.map(item => {
              let {task_type, build_nums} = item
              let task_type_str = this.taskTypes.find(tt => tt.value === task_type).label
              let build_nums_str = build_nums.sort().map(num => this.buildings.find(build => build.value === num).label.charAt(0)).join(" | ")
              return {...item, task_type_str, build_nums_str}
            })
          }).catch(err => this.$message.error(err.message))
          .finally(() => this.loadingList = false)
    },
    deleteTaskById(task) {
      this.$confirm(`确认删除【${task.task_title}】？`, '确认信息').then(res => {
        this.$db.collection("plot-task").doc(task._id).remove().then(res => {
          this.$message.success("删除成功！")
          this.getTaskList()
        }).catch(err => this.$message.error(err.message))
      })
    },
    deleteTaskBatch() {
      this.$confirm("确认删除选中项？", '确认信息').then(res => {
        this.$db.collection("plot-task").where({_id: this.$dbCmd.in(this.selTaskIds)}).remove().then(res => {
          this.$message.success("删除成功！")
          this.getTaskList()
        }).catch(err => this.$message.error(err.message))
      })
    },
    updateTaskState(task, flag) {
      let state = flag === '发布' ? '1' : '0'
      this.$confirm(`确认${flag}【${task.task_title}】任务？`, '确认信息').then(res => {
        this.$db.collection("plot-task").doc(task._id).update({state}).then(res => {
          this.$message.success(`${flag}成功！`)
          this.getTaskList()
        }).catch(err => this.$message.error(err.message))
      })
    }
  }
}
</script>

<style scoped>
.info-select {
  width: 120px;
  margin: 5px
}

.total-view {
  font-size: 13px;
  margin-top: 3px;
  margin-right: 10px;
  color: #606266;
}
</style>
